import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "LoadServlet", urlPatterns = "/uploadp")
public class LoadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("text/html;charset=utf-8");
        response.setContentType("utf-8");
        if (!ServletFileUpload.isMultipartContent(request)) {
            return;
        }

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        String path = getServletContext().getRealPath("") + File.separator + "upload";
        File uploadDir = new File(path);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }


        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            if (fileItems != null && fileItems.size() > 0) {
                for (FileItem fileItem : fileItems) {
                    String fileName = new File(fileItem.getName()).getName();
                    String filepath = path + File.separator + fileName;
                    File file = new File(filepath);
                    fileItem.write(file);
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
